from flask import Flask, request
from flask_sqlalchemy import SQLAlchemy
import random

nodes = []
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI']="sqlite:///nodes.db"
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"]=False
db = SQLAlchemy(app)


class NodeModel(db.Model):
    ip = db.Column(db.String(17),primary_key=True,nullable = False)
    region = db.Column(db.String(10),primary_key=True,nullable = False)
    free_space = db.Column(db.Integer,primary_key=True,nullable = False)
    user_name = db.Column(db.String(64))
    password = db.Column(db.String(64))

    def __repr__(self):
        return self.ip+":"+self.region+":"+str(self.free_space)

@app.route("/reg")
def registrate():
    ip=request.args.get("ip")
    region = request.args.get("rg")
    free_space = 0
    found = False
    nodes = NodeModel.query.order_by(NodeModel.free_space).all()
    try:
        for node in nodes:
            if node.ip==ip and node.region==region:
               found = True
               break
        if found==False:
            node = NodeModel(ip=ip,region=region,free_space=free_space)
            db.session.add(node)
            db.session.commit()
            return "OK"
    except:
        return "Error while registration"

@app.route("/nodes_list")
def list_nodes():
    nodes = NodeModel.query.order_by(NodeModel.free_space).all()
    o=""
    for node in nodes:
        o+=node.ip+","
    return o
@app.route("/listip")
def list_ip():
    nodes = NodeModel.query.order_by(NodeModel.free_space).all()
    o=""
    for node in nodes:
        o+=node.ip+"\n"
    return o
    

@app.route("/get_best_node")
def get_best_node():
    nodes = NodeModel.query.order_by(NodeModel.free_space).all()
    return str(f"{nodes[len(nodes)-1].ip},{nodes[len(nodes)-1].user_name},{nodes[len(nodes)-1].password}")

@app.route("/update-info")
def update_node_info():
    ip=request.args.get("ip")
    region = request.args.get("rg")
    free_space = request.args.get("free_space")
    nodes = NodeModel.query.order_by(NodeModel.free_space).all()
    for i in range(len(nodes)):
        if nodes[i].ip == ip and nodes[i].region == region:
            nodes[i].free_space = free_space
            db.session.commit()
            return "OK"
        break
    return "ERROR - NODE NOT FOUND"+str(nodes)
@app.route("/delbase")
def clear_all():
    nodes = NodeModel.query.order_by(NodeModel.free_space).all()
    for node in nodes:
        db.session.delete(node)
    db.session.commit()
    return "Ok"
    
if __name__=="__main__":
    app.run(debug=True,host="0.0.0.0",port=8920)